package CanvaWeb.CanvaWeb.Controller;

import CanvaWeb.CanvaWeb.Repository.RoomMemberRepository;
import CanvaWeb.CanvaWeb.Repository.RoomRepository;
import CanvaWeb.CanvaWeb.Repository.UserRepository;
import CanvaWeb.CanvaWeb.Service.RoomService;
import CanvaWeb.CanvaWeb.pojo.Room;
import CanvaWeb.CanvaWeb.pojo.RoomStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
@RequestMapping("/room")
public class RoomController {

    @Autowired
    private RoomRepository roomRepository;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private RoomService roomService;

    @Autowired
    private RoomMemberRepository roomMemberRepository;

    // 创建房间
    @PostMapping("/create")
    public ResponseEntity<Map<String, Object>> createRoom(@RequestParam String name, @RequestParam Integer capacity) {
        try {
            Room room = roomService.createRoom(name, capacity);
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("room", room);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "创建房间失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    // 加入房间
    @PostMapping("/{roomId}/join")
    public ResponseEntity<Map<String, Object>> joinRoom(@PathVariable Long roomId, @RequestBody Map<String, Object> requestData) {
        // 从请求体中获取 userId，防止类型转换错误
        Integer userIdInteger = (Integer) requestData.get("userId");  // 这里返回 Integer 类型
        Long userId = userIdInteger != null ? userIdInteger.longValue() : null;  // 转换为 Long 类型

        // 判断 userId 是否为空
        if (userId == null) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "用户未登录！");
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
        }

        Map<String, Object> response = new HashMap<>();
        try {
            // 调用 service 层将用户加入房间
            roomService.joinRoom(roomId, userId);

            // 获取房间信息
            Room room = roomRepository.findById(roomId).orElseThrow(() -> new RuntimeException("房间未找到"));

            // 检查房间人数是否达到最大容量
            if (room.getCurrentPlayers() >= room.getCapacity()) {
                // 如果人数已满，设置房间状态为 "READY_TO_START"
                room.setStatus(RoomStatus.READY_TO_START);
                roomRepository.save(room); // 保存更新后的房间状态
                response.put("message", "房间已满，状态更新为准备开始游戏！");
            }

            response.put("success", true);
            response.put("message", "加入房间成功");
            return ResponseEntity.ok(response);
        } catch (RuntimeException e) {
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    @GetMapping("/{roomId}")
    public ResponseEntity<Map<String, Object>> getRoomStatus(@PathVariable Long roomId) {
        Map<String, Object> response = new HashMap<>();
        try {
            Room room = roomService.getRoomById(roomId);
            if (room == null) {
                response.put("success", false);
                response.put("message", "房间不存在");
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(response);
            }

            // 查询该房间的成员数
            long playerCount = roomMemberRepository.countByRoomId(roomId);
            RoomStatus status = room.getStatus();

            response.put("success", true);
            response.put("status", status);
            response.put("playerCount", playerCount);

            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "查询失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }
    // 获取房间列表
    @GetMapping("/list")
    public ResponseEntity<List<Room>> getRoomList() {
        List<Room> rooms = roomService.getRoomList();
        return ResponseEntity.ok(rooms);
    }

    @GetMapping("/search")
    public ResponseEntity<List<Room>> searchRoomsByName(@RequestParam String name) {
        List<Room> rooms = roomService.searchRoomsByName(name);
        if (rooms.isEmpty()) {
            return ResponseEntity.status(404).body(null);
        }
        return ResponseEntity.ok(rooms);
    }

    // 角色变更接口
    @PostMapping("/{roomId}/users/{userId}/change-role")
    public ResponseEntity<Map<String, Object>> changeUserRole(
            @PathVariable Long roomId,
            @PathVariable Long userId,
            @RequestParam String role) {

        Map<String, Object> response = new HashMap<>();

        try {
            // 检查角色是否合法
            if (!role.equals("DRAWER") && !role.equals("GUESSER")) {
                response.put("success", false);
                response.put("message", "无效的角色，必须是 'DRAWER' 或 'GUESSER'");
                return ResponseEntity.badRequest().body(response);
            }

            // 调用服务层进行角色更改
            roomService.changeUserRole(roomId, userId, role);

            response.put("success", true);
            response.put("message", "角色更改成功");
            return ResponseEntity.ok(response);

        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "角色更改失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }

    @GetMapping("/{roomId}/users/{userId}/role")
    public ResponseEntity<?> getUserRole(@PathVariable Long roomId, @PathVariable Long userId) {
        try {
            // 调用 Service 层来获取角色
            String role = roomService.getUserRole(roomId, userId);

            if (role != null) {
                return ResponseEntity.ok(role); // 返回角色
            } else {
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body("用户未在该房间中");
            }
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("获取用户角色失败: " + e.getMessage());
        }
    }
}


